package com.wanpinghui.supplier.message;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.SharedElementCallback;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.bumptech.glide.DrawableRequestBuilder;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.business.view.PinchImageView;
import com.wanpinghui.supplier.widgets.BaseAnimCloseViewPager;
import com.wanpinghui.supplier.widgets.ScaleViewPager;
import com.wanpinghui.supplier.widgets.SpinView;
import com.wanpinghui.wphlibrary.common.dialog.LoadingDialog;
import com.wanpinghui.wphlibrary.model.base.bean.CacheImage;
import com.wanpinghui.wphlibrary.model.glide.CustomImageModelLoader;
import com.wanpinghui.wphlibrary.model.glide.CustomImageSizeModel;
import com.wanpinghui.wphlibrary.model.glide.CustomImageSizeModelImp;
import com.wanpinghui.wphlibrary.model.message.bean.MessagesExt;
import com.yunshl.yunshllibrary.storage.ShareDataManager;
import com.yunshl.yunshllibrary.utils.TextUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;


/**
 */
public class PhotoBrowseActivity extends AppCompatActivity {


    private int firstDisplayImageIndex = 0;
    private boolean newPageSelected = false;
    //private PinchImageView mCurImage;
    private ScaleViewPager imageViewPager;
    private List<String> pictureList;
    private ProgressBar progressBar;

    PagerAdapter adapter;
    private String messagesExt;

    boolean canDrag = false;
    private SpinView pb;

    public static void startWithElement(Activity context, ArrayList<String> urls,
                                        int firstIndex, View view, String ext) {
        Intent intent = new Intent(context, PhotoBrowseActivity.class);
        intent.putStringArrayListExtra("urls", urls);
        intent.putExtra("index", firstIndex);
        intent.putExtra("ext", ext);
        ActivityOptionsCompat compat = null;
        if (view == null) {
            compat = ActivityOptionsCompat.makeSceneTransitionAnimation(context);
        } else {
            compat = ActivityOptionsCompat.makeSceneTransitionAnimation(context, view,
                    "tansition_view");
        }
        ActivityCompat.startActivity(context, intent, compat.toBundle());
    }

    public static void startWithElement1(Activity context, ArrayList<String> urls,
                                        int firstIndex, View view, String ext) {
        Intent intent = new Intent(context, PhotoBrowseActivity.class);
        intent.putStringArrayListExtra("urls", urls);
        intent.putExtra("index", firstIndex);
        intent.putExtra("ext", ext);
//        ActivityOptionsCompat compat = null;
//        if (view == null) {
//            compat = ActivityOptionsCompat.makeSceneTransitionAnimation(context);
//        } else {
//            compat = ActivityOptionsCompat.makeSceneTransitionAnimation(context, view,
//                    "tansition_view");
//        }
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_photo_browse);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        initView();
    }

    public void initView() {
        pictureList = getIntent().getStringArrayListExtra("urls");
        firstDisplayImageIndex = Math.min(getIntent().getIntExtra("index", firstDisplayImageIndex), pictureList.size());
        messagesExt = getIntent().getStringExtra("ext");

        imageViewPager = (ScaleViewPager) findViewById(R.id.viewpager);
        setViewPagerAdapter();
        imageViewPager.setOffscreenPageLimit(5);
        setEnterSharedElementCallback(new SharedElementCallback() {

            @Override
            public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
                ViewGroup layout = (ViewGroup) imageViewPager.findViewWithTag(imageViewPager.getCurrentItem());
                if (layout == null) {
                    return;
                }
                View sharedView = layout.findViewById(R.id.image_view);
                sharedElements.clear();
                sharedElements.put("tansition_view", sharedView);
            }
        });
    }

    private void setViewPagerAdapter() {
        adapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return pictureList == null ? 0 : pictureList.size();
            }

            @Override
            public void notifyDataSetChanged() {
                super.notifyDataSetChanged();
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                View layout = (View) object;
                container.removeView(layout);
            }

            @Override
            public void setPrimaryItem(ViewGroup container, int position, Object object) {
                super.setPrimaryItem(container, position, object);
                try {
                    imageViewPager.setCurrentShowView(((View)object).findViewById(R.id.image_view));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return (view == object);
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View layout;
                layout = LayoutInflater.from(PhotoBrowseActivity.this).inflate(R.layout.layout_browse, null);
                pb = (SpinView) layout.findViewById(R.id.pb);
                View view = layout.findViewById(R.id.view);
                PinchImageView imageView = (PinchImageView) layout.findViewById(R.id.image_view);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            finishAfterTransition();
                        } else {
                            finish();
                        }
                    }
                });
                container.addView(layout);
                layout.setTag(position);
                if (position == firstDisplayImageIndex) {
                    onViewPagerSelected(position);
                }
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finishAfterTransition();
                    }
                });
                setImageView(pictureList.get(position),imageView);
                return layout;

            }

            @Override
            public int getItemPosition(Object object) {
                return POSITION_NONE;
            }
        };

        imageViewPager.setAdapter(adapter);
        imageViewPager.setOffscreenPageLimit(1);
        imageViewPager.setCurrentItem(firstDisplayImageIndex);
        imageViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                if (positionOffset == 0f && newPageSelected) {
//                    newPageSelected = false;
//                    onViewPagerSelected(position);
//                }
            }

            @Override
            public void onPageSelected(int position) {
                //newPageSelected = true;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        imageViewPager.setiAnimClose(new BaseAnimCloseViewPager.IAnimClose() {
            @Override
            public boolean canDrag() {
                return canDrag;
            }

            @Override
            public void onPictureClick() {
                finishAfterTransition();
            }

            @Override
            public void onPictureRelease(View view) {
                finishAfterTransition();
            }
        });
    }


    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finishAfterTransition();
        }
    };


    private void onViewPagerSelected(int position) {
        //updateCurrentImageView(position);
        //setImageView(pictureList.get(position));
    }


    /**
     * 设置图片
     *
     * @param path
     */
    private void setImageView(final String path, PinchImageView imageView) {
        if (imageView.getDrawable() != null)//判断是否已经加载了图片，避免闪动
            return;
        if (TextUtils.isEmpty(path)) {
            imageView.setBackgroundColor(Color.GRAY);
            return;
        }
        canDrag = false;
        if (messagesExt != null) {
            setMsg(path,imageView);
        } else {
            progressBar.setVisibility(View.VISIBLE);
            pb.setVisibility(View.GONE);
            Glide.with(this).load(path).error(R.mipmap.goods_bg_loading).listener(new RequestListener<String, GlideDrawable>() {
                @Override
                public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                    progressBar.setVisibility(View.GONE);
                    return false;
                }

                @Override
                public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    progressBar.setVisibility(View.GONE);
                    return false;
                }
            }).diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
        }
    }

    public void setMsg(final String msg,final PinchImageView imageView) {
        // pb.setVisibility(View.VISIBLE);
        MessagesExt ext = MessagesExt.getMessagesExt(messagesExt);
        String path = null;
        if (TextUtil.isNotEmpty(ext.getFile_path()) && new File(ext.getFile_path()).exists()) {
            path = ext.getFile_path();
            Glide.with(this).load(path).placeholder(R.mipmap.goods_bg_loading_a).listener(new RequestListener<String, GlideDrawable>() {
                @Override
                public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                    // Util.showToast(mContext, "图片加载失败");
                    //         showWarningText("图片加载失败");
                    imageView.setImageResource(R.mipmap.goods_bg_loading);
                    pb.setVisibility(View.GONE);
                    return false;
                }

                @Override
                public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    //    Util.showToast(mContext, "图片加载成功");
                    pb.setVisibility(View.GONE);
                    return false;
                }//这个用于监听图片是否加载完成
            }).diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
        } else {
            path = msg + "_thumbnail";
            displayImage(new CustomImageSizeModelImp(msg), new CustomImageSizeModelImp(path), imageView, pb);
            //   BitmapUtilManager.getInstance().loadImage(getApplicationContext(),mCurImage,msg);

//                Glide.with(getApplicationContext()).load(new CacheImage(path))
//                        .listener(new RequestListener<CacheImage, GlideDrawable>() {
//                            @Override
//                            public boolean onException(Exception e, CacheImage model, Target<GlideDrawable> target, boolean isFirstResource) {
//                                showWarningText("图片加载失败");
//                                pb.setVisibility(View.GONE);
//                                return false;
//                            }
//
//                            @Override
//                            public boolean onResourceReady(GlideDrawable resource, CacheImage model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
//                                showimage(resource, msg);
//                                return false;
//                            }
//                        }).
//                        skipMemoryCache(true).
//                        diskCacheStrategy(DiskCacheStrategy.ALL).into(mCurImage);
        }
    }

    void displayImage(final CustomImageSizeModel model, final CustomImageSizeModel model_, final ImageView imageView, final SpinView pb) {
        pb.setVisibility(View.VISIBLE);
        DrawableRequestBuilder thumbnailBuilder = Glide
                .with(imageView.getContext())
                .load(new CustomImageSizeModelImp(model_
                        .getBaseUrl())
                        .requestCustomSizeUrl(200, 300))
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.RESULT);

        Glide.with(getApplicationContext())
                .using(new CustomImageModelLoader(imageView.getContext()))
                .load(model)
//                    .load(model.getBaseUrl())
//                .centerCrop()
                .listener(new RequestListener<CustomImageSizeModel, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, CustomImageSizeModel model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, final CustomImageSizeModel model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        pb.setVisibility(View.GONE);
//                        new  Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                String path = getImgPathFromCache(model.getBaseUrl());
//                                LogUtils.e("getImgPathFromCache:  ",path);
//                            }
//                        }).start();
//                            mAttacher.update();
                        return false;
                    }
                })
                .thumbnail(thumbnailBuilder)
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .into(imageView);
    }

    private String getImgPathFromCache(String msg) {
        FutureTarget<File> futureTarget = Glide.with(getApplicationContext()).load(msg).downloadOnly(100, 100);
        try {
            File cacheFile = futureTarget.get();
            String path = cacheFile.getAbsolutePath();
            return path;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }


    private void showimage(GlideDrawable resource, String msg) {
//        Glide.with(getApplicationContext()).load(new CacheImage(msg))
//                .placeholder(resource).
//                diskCacheStrategy(DiskCacheStrategy.ALL).
//                skipMemoryCache(true).
//                listener(new RequestListener<CacheImage, GlideDrawable>() {
//                    @Override
//                    public boolean onException(Exception e, CacheImage model, Target<GlideDrawable> target, boolean isFirstResource) {
//                        ShareDataManager.getInstance().save(getApplicationContext(), "isSuccess", null);
//                        //           showWarningText("图片加载失败");
//                        pb.setVisibility(View.GONE);
//                        return false;
//                    }
//
//                    @Override
//                    public boolean onResourceReady(GlideDrawable resource, CacheImage model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
//                        ShareDataManager.getInstance().save(getApplicationContext(), "isSuccess", "1");
//                        pb.setVisibility(View.GONE);
//                        return false;
//                    }
//                }).into(mCurImage);
    }

    // 初始化每个view的image
    protected void updateCurrentImageView(final int position) {
//        View currentLayout = imageViewPager.findViewWithTag(position);
//        if (currentLayout == null) {
//            ViewCompat.postOnAnimation(imageViewPager, new Runnable() {
//
//                @Override
//                public void run() {
//                    updateCurrentImageView(position);
//                }
//            });
//            return;
//        }
//        mCurImage = (PinchImageView) currentLayout.findViewById(R.id.image_view);
//        mCurImage.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finishAfterTransition();
//            }
//        });
//        imageViewPager.setCurrentShowView(mCurImage);
    }


    @Override
    public void finishAfterTransition() {
        Intent intent = new Intent();
        intent.putExtra("index", imageViewPager.getCurrentItem());
        setResult(RESULT_OK, intent);
        super.finishAfterTransition();
    }
}
